from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from typing import List

from app.api.deps import get_current_user
from app.db.session import get_db
from app.crud import user as user_crud
from app.schemas.user import UserProfile, FavoriteItem, HistoryItem
from app.models.user import User

router = APIRouter()

@router.get("/me", response_model=UserProfile)
def get_user_profile(current_user: User = Depends(get_current_user)):
    """获取当前用户信息"""
    return current_user

@router.put("/me", response_model=UserProfile)
def update_user_profile(
    profile: dict,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户信息"""
    return user_crud.update_user(db, current_user, **profile)

@router.post("/avatar")
async def update_avatar(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户头像"""
    # TODO: 实现文件上传和存储逻辑
    # 这里应该处理文件上传，保存文件，并更新用户头像URL
    return {"message": "头像更新成功"}

@router.get("/favorites", response_model=List[FavoriteItem])
def get_favorites(
    skip: int = 0,
    limit: int = 20,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户收藏列表"""
    return user_crud.get_user_favorites(db, current_user.id, skip, limit)

@router.post("/favorites/{node_id}")
def add_to_favorites(
    node_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """添加收藏"""
    favorite = user_crud.add_favorite(db, current_user.id, node_id)
    return {"message": "收藏成功"}

@router.delete("/favorites/{node_id}")
def remove_from_favorites(
    node_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消收藏"""
    success = user_crud.remove_favorite(db, current_user.id, node_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="收藏项不存在"
        )
    return {"message": "取消收藏成功"}

@router.get("/history", response_model=List[HistoryItem])
def get_history(
    skip: int = 0,
    limit: int = 20,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取浏览历史"""
    return user_crud.get_user_history(db, current_user.id, skip, limit)

@router.post("/history/{node_id}")
def add_to_history(
    node_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """添加浏览历史"""
    history = user_crud.add_history(db, current_user.id, node_id)
    return {"message": "添加历史记录成功"}

@router.delete("/history")
def clear_history(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """清空浏览历史"""
    success = user_crud.clear_history(db, current_user.id)
    return {"message": "清空历史记录成功"} 